#include "BinaryTree.h"
#include "Queue.h"

TreeNode* BinaryTreeCreate(BTDataType* a, int* pi)
{
	if (a[*pi] == "#")
	{
		(*pi)++;
		return NULL;
	}

	TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
	if (root == NULL)
	{
		perror("malloc fail");
	}

	root->data = a[(*pi)++];
	root->left = BinaryTreeCreate(a, pi);
	root->right = BinaryTreeCreate(a, pi);

	return root;
}


void BinaryTreeDestory(TreeNode* root)
{
	if (root == NULL)
	{
		return;
	}
	
	BinaryTreeDestory(root->left);
	BinaryTreeDestory(root->right);
	free(root);
}


void BinaryTreePrevOrder(TreeNode* root)
{
	{
		if (root == NULL)
		{
			printf("# ");
			return;
		}

		printf("%d ", root->data);
		BinaryTreePrevOrder(root->left);
		BinaryTreePrevOrder(root->right);
	}
}

int BinaryTreeSize(TreeNode* root)
{
	return root == NULL ? 0 :
		TreeSize(root->left) +
		TreeSize(root->right) + 1;
}

int BinaryTreeLeafSize(TreeNode* root)
{
	
	if (root == NULL)
		return 0;
	
	if (root->left == NULL
		&& root->right == NULL)
		return 1;

	return TreeLeafSize(root->left) +
		TreeLeafSize(root->right);
}

int BinaryTreeLevelKSize(TreeNode* root, int k)
{
	assert(k > 0);
	if (root == NULL)
		return 0;

	if (k == 1)
		return 1;

	return TreeLevelK(root->left, k - 1)
		+ TreeLevelK(root->right, k - 1);
}

TreeNode* BinaryTreeFind(TreeNode* root, BTDataType x)
{
	if (root == NULL)
		return NULL;

	if (root->data == x)
		return root;

	TreeNode* ret1 = TreeFind(root->left, x);
	if (ret1)
		return ret1;

	TreeNode* ret2 = TreeFind(root->right, x);
	if (ret2)
		return ret2;

	return NULL;
}

int BinaryTreeComplete(TreeNode* root)
{
	Queue q;
	QueueInit(&q);
	if (root)
		QueuePush(&q, root);

	int levelSize = 1;
	while (!QueueEmpty(&q))
	{
		TreeNode* front = QueueFront(&q);
		QueuePop(&q);

		if (front == NULL)
			break;

		QueuePush(&q, front->left);
		QueuePush(&q, front->right);
	}

	// 前面遇到空以后，后面还有非空就不是完全二叉树
	while (!QueueEmpty(&q))
	{
		TreeNode* front = QueueFront(&q);
		QueuePop(&q);

		if (front)
		{
			QueueDestroy(&q);
			return false;
		}
	}

	QueueDestroy(&q);
	return true;
}

//void BinaryTreeLevelOrder(TreeNode* root)
//{
//	Queue q;
//	QueueInit(&q);
//	if (root)
//		QueuePush(&q, root);
//
//	int levelSize = 1;
//	while (!QueueEmpty(&q))
//	{
//		// 一层一层出
//		while (levelSize--)
//		{
//			TreeNode* front = QueueFront(&q);
//			QueuePop(&q);
//
//			printf("%d ", front->data);
//
//			if (front->left)
//				QueuePush(&q, front->left);
//
//			if (front->right)
//				QueuePush(&q, front->right);
//		}
//		printf("\n");
//
//		levelSize = QueueSize(&q);
//	}
//	printf("\n");
//
//	QueueDestroy(&q);
//}

int main()
{
	
	return 0;
}